<%--
  Created by IntelliJ IDEA.
  User: 15167
  Date: 2024/12/13
  Time: 15:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>学习交流中心</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <script src="https://unpkg.com/vue@3"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/element-plus"></script>

    <style>
        body {
            margin: 0;
        }

        #app {
            margin: 0;
        }

        .title {
            color: white;
        }

        .header {
            display: flex;
            align-items: center;
            background: #409eff;
        }

        .login_register_link, .login_register_link * {
            color: white;
        }

        .main {
            display: flex;
            justify-content: center;
            background: rgb(235.9, 245.3, 255);
        }

        .footer {
            background: #409eff;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
        }

        .main .content {
            width: 1000px;
        }

        .main .content .recommend {
            width: 400px;
            height: 400px;
        }

        .cover {
            border-radius: 20px;
            background: white;
        }

        .cover:hover {
            cursor: pointer;
            transform: scale(1.03);
        }

        .main .main-header {
            display: flex;
        }

        .main .other-recommend .row {
            display: flex;
        }

        .main .other-recommend .cover {
            width: 185px;
            height: 185px;
            margin: 15px;
        }

        .main .content .buttons {
            margin-top: 50px;
            display: flex;
            justify-content: space-between;
        }

        .main .content .buttons .btn {
            height: 50px;
            width: 200px;
            font-size: 20px;
        }

        .el-carousel__item h3 {
            color: #475669;
            opacity: 0.75;
            line-height: 200px;
            margin: 0;
            text-align: center;
        }

        .popular-rooms {
            margin-top: 50px;
            margin-bottom: 25px;
        }

        .popular-rooms .carousel {
            background: white;
        }

        .message-box {
            display: flex;
            margin: 10px 0;
        }

        .message-box div {

        }

        .message-box .content {
            margin: 0 10px;
            display: flex;
            align-items: center;
            word-break: break-all;
        }

        .system-message {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 10px 0;
            color: red;
        }

        .chat-name-box {
            font-weight: bold;
            font-size: 20px;
            width: 100px;
            display: flex;
            justify-content: right
        }

        .chat-name {
            font-weight: bold;
            font-size: 20px;
            text-overflow: ellipsis;
            text-wrap: nowrap;
            overflow: hidden
        }
    </style>
</head>
<body>
<div id="app">
    <div class="common-layout">
        <el-container>
            <el-header class="header">
                <div class="el-col-20" style="display: flex;align-items: center">
                    <h1 class="title">学习交流中心</h1>
                    <div v-if="adminMode.isAdmin">
                        <label style="font-weight: bold;margin-left:100px;color: white">
                            管理员模式:
                            <el-switch v-model="adminMode.openAdminMode"
                                       style="--el-switch-on-color: #ff4949;--el-switch-off-color:#faa"/>
                        </label>
                    </div>
                    <div v-if="adminMode.openAdminMode">
                        <el-link style="color: white;margin-left: 50px;font-weight: bold" type="primary"
                                 @click="userListDialog.openDialog()">*管理用户
                        </el-link>
                    </div>
                </div>
                <div class="login_register_link">
                    <div v-if="userinfo == null">
                        <el-link @click="loginDialog.openDialog()">登录</el-link>
                        |
                        <el-link @click="registerDialog.openDialog()">注册</el-link>
                    </div>
                    <div v-else>
                        <el-link><span>用户:<span style="font-weight: bold">{{userinfo.username}}</span></span>
                        </el-link>
                        |
                        <el-link @click="logout()">退出登录</el-link>
                    </div>
                </div>
            </el-header>
            <el-main class="main">
                <div class="content">
                    <div class="main-header">
                        <div>
                            <el-tooltip
                                    class="box-item"
                                    effect="dark"
                                    content="综合聊天室"
                                    placement="bottom"
                            >
                                <el-image class="recommend cover"
                                          src="static/img/世界综合聊天室封面.png"
                                          :fit="fit" @click="testEnterChatRoom(1000)"></el-image>
                            </el-tooltip>
                        </div>
                        <div class="other-recommend">
                            <div class="row">
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="游戏聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="cover" style="width: 100%; height: 100%"
                                              src="static/img/世界游戏聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1003)"></el-image>
                                </el-tooltip>
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="生活聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="cover" style="width: 100%; height: 100%"
                                              src="static/img/世界生活聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1004)"></el-image>
                                </el-tooltip>
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="学习聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="cover" style="width: 100%; height: 100%"
                                              src="static/img/世界学习聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1001)"></el-image>
                                </el-tooltip>
                            </div>
                            <div class="row">
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="阅读聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="cover" style="width: 100%; height: 100%"
                                              src="static/img/世界阅读聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1006)"></el-image>
                                </el-tooltip>
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="艺术聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="cover" style="width: 100%; height: 100%"
                                              src="static/img/世界艺术聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1005)"></el-image>
                                </el-tooltip>
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="影音聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="cover" style="width: 100%; height: 100%"
                                              src="static/img/世界影音聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1002)"></el-image>
                                </el-tooltip>
                            </div>
                        </div>
                    </div>
                    <div class="buttons">
                        <el-button class="btn" type="primary" @click="editChatRoomDialog.openDialog('创建聊天室')">
                            创建聊天室
                        </el-button>
                        <el-button class="btn" type="primary" @click="joinChatRoomDialog.openDialog()">加入聊天室
                        </el-button>
                        <el-button class="btn" type="primary" @click="myChatRoomDialog.openDialog()">我的聊天室
                        </el-button>
                        <el-button class="btn" type="primary" @click="chatRoomFootprintsDialog.openDialog()">聊天室足迹
                        </el-button>
                    </div>
                    <div class="popular-rooms">
                        <el-carousel :interval="4000" type="card" height="350px">
                            <el-carousel-item>
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="学习聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="cover" style="width: 100%; height: 100%"
                                              src="static/img/世界学习聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1001)"></el-image>
                                </el-tooltip>
                            </el-carousel-item>
                            <el-carousel-item>
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="阅读聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="cover" style="width: 100%; height: 100%"
                                              src="static/img/世界阅读聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1006)"></el-image>
                                </el-tooltip>
                            </el-carousel-item>
                            <el-carousel-item>
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="影音聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="cover" style="width: 100%; height: 100%"
                                              src="static/img/世界影音聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1002)"></el-image>
                                </el-tooltip>
                            </el-carousel-item>
                            <el-carousel-item>
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="综合聊天室"
                                        placement="bottom"
                                >
                                    <el-image class="recommend cover"
                                              src="static/img/世界综合聊天室封面.png"
                                              :fit="fit" @click="testEnterChatRoom(1000)"></el-image>
                                </el-tooltip>
                            </el-carousel-item>
                        </el-carousel>
                    </div>
                </div>
            </el-main>
            <el-footer class="footer">该程序由fdhwws编写</el-footer>
        </el-container>
    </div>


    <el-dialog :title="editChatRoomDialog.title" v-model="editChatRoomDialog.show" width="400"
               @close="editChatRoomDialog.closeDialog()">
        <el-form>
            <el-form-item label="房间名称* :">
                <el-input v-model="editChatRoomDialog.data.name" type="text" placeholder="请输入房间名称"/>
            </el-form-item>
            <el-form-item label="访问权限* :">
                <el-select v-model="editChatRoomDialog.data.access" placeholder="请选择访问权限">
                    <el-option label="公开" :value="1"></el-option>
                    <el-option label="私密" :value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="访问密码* :" v-show="editChatRoomDialog.data.access == 0">
                <el-input v-model="editChatRoomDialog.data.password" type="password"
                          placeholder="请输入访问密码"/>
            </el-form-item>
            <el-form-item label="预览封面" v-if="editChatRoomDialog.title.indexOf('修改') >= 0">
                <el-image :src="editChatRoomDialog.data.pic" style="width: 100px;height: 100px"/>
            </el-form-item>
            <el-form-item label="聊天房封面 :">
                <input id="file_pic_create_room" @change="editChatRoomDialog.handleFileChange()" type="file"
                       accept="image/*">
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="editChatRoomDialog.addNewRoom()">创建</el-button>
            <el-button @click="editChatRoomDialog.show = false">取消</el-button>
        </template>
    </el-dialog>


    <el-dialog title="加入房间" v-model="joinChatRoomDialog.show" width="400" @close="joinChatRoomDialog.closeDialog()">
        <el-form>
            <el-form-item label="加入方式* :">
                <el-select v-model="joinChatRoomDialog.choose" placeholder="请选择访问权限"
                           @change="joinChatRoomDialog.handleChoose">
                    <el-option label="房间名称" value="1"></el-option>
                    <el-option label="房间id" value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="房间名称* :" v-if="joinChatRoomDialog.choose == 1">
                <el-autocomplete
                        v-model="joinChatRoomDialog.data.search"
                        :fetch-suggestions="joinChatRoomDialog.querySearch"
                        popper-class="my-autocomplete"
                        placeholder="请输入房间名称"
                        @select="joinChatRoomDialog.handleSelect"
                >
                    <template #default="{ item }">
                        <div class="value" style="font-weight: bold">{{ item.name }}</div>
                        <span class="link">
                            <span style="margin-right: 10px">房间id: {{ item.id }}</span>
                            <span v-if="item.access == 1"><el-tag size="small">公开</el-tag></span>
                                <span v-if="item.access == 0"><el-tag size="danger">私密</el-tag></span>
                        </span>
                        <span v-if="adminMode.openAdminMode" style="margin-left: 10px">
                            <span v-if="item.valid"><el-tag
                                    size="small">有效</el-tag></span>
                                <span v-if="!item.valid"><el-tag size="danger">无效</el-tag>
                                </span>
                        </span>
                    </template>
                </el-autocomplete>
            </el-form-item>
            <el-form-item label="房间id* :" label-width="80" v-if="joinChatRoomDialog.choose == 0">
                <el-input v-model="joinChatRoomDialog.data.search" type="number" placeholder="请输入房间id"
                          @keydown.enter="joinChatRoomDialog.handleSubmit"/>
            </el-form-item>
            <div>
                <div style="font-weight: bold">搜索结果:</div>
                <div v-show="joinChatRoomDialog.data.name != null">
                    <div style="display: flex">
                        <el-image style="width: 150px; height: 150px"
                                  :src="joinChatRoomDialog.data.pic"></el-image>
                        <div style="margin-left: 10px">
                            <div>房间名称:{{joinChatRoomDialog.data.name}}</div>
                            <div>房间id :{{joinChatRoomDialog.data.id}}</div>
                            <div><span v-if="joinChatRoomDialog.data.access == 1"><el-tag
                                    size="small">公开</el-tag></span>
                                <span v-if="joinChatRoomDialog.data.access == 0"><el-tag
                                        size="danger">私密</el-tag></span></div>
                            <div>
                                <el-link type="primary" @click="testEnterChatRoom(joinChatRoomDialog.data.id)">
                                    进入聊天室
                                </el-link>
                            </div>
                            <div v-if="adminMode.openAdminMode">
                                <div>
                                    <div>房间创建者id:{{ joinChatRoomDialog.data.createUserId }}</div>
                                    <div>房间创建者用户名:{{ joinChatRoomDialog.data.username }}</div>
                                </div>
                                <div>
                                    房间状态:
                                    <span v-if="joinChatRoomDialog.data.valid"><el-tag
                                            size="small">正常</el-tag></span>
                                    <span v-if="!joinChatRoomDialog.data.valid"><el-tag
                                            size="danger">无效</el-tag></span>
                                </div>
                                <el-link style="color: red" type="primary"
                                         @click="joinChatRoomDialog.openOrCloseRoom(joinChatRoomDialog.data.id)">
                                    开启/关闭聊天室
                                </el-link>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div v-show="joinChatRoomDialog.data.name == null">
                <div style="font-weight: bold;color: red;display: flex;justify-content: center">
                    <strong>无结果</strong></div>
            </div>
        </el-form>
    </el-dialog>


    <el-dialog title="我的聊天室" v-model="myChatRoomDialog.show" width="600" @open="myChatRoomDialog.update()">
        <div style="overflow: auto;max-height: 400px">
            <div v-if="myChatRoomDialog.data.length == 0" style="display: flex;justify-content: center">
                <strong style="font-size: 20px;color: red">无房间</strong>
            </div>
            <div v-for="item in myChatRoomDialog.data">
                <el-popover placement="right" trigger="hover">
                    <template #reference>
                        <el-descriptions title="房间信息">
                            <el-descriptions-item label="房间名称">{{item.name}}</el-descriptions-item>
                            <el-descriptions-item label="房间id">{{item.id}}</el-descriptions-item>
                            <el-descriptions-item label="房间权限">
                                <span v-if="item.access == 1"><el-tag size="small">公开</el-tag></span>
                                <span v-if="item.access == 0"><el-tag size="danger">私密</el-tag></span>
                            </el-descriptions-item>
                            <el-descriptions-item label="房间密码">
                                <el-input show-password readonly v-model="item.password" type="password"
                                          style="width: 150px"/>
                            </el-descriptions-item>
                            <el-descriptions-item label="操作">
                                <el-link type="success" @click="testEnterChatRoom(item.id)">加入</el-link>
                                |
                                <el-link type="primary" @click="myChatRoomDialog.modifyRoom(item)">修改
                                </el-link>
                                |
                                <el-popconfirm title="确认删除?" @confirm="myChatRoomDialog.deleteRoom(item.id)">
                                    <template #reference>
                                        <el-link type="danger">删除</el-link>
                                    </template>
                                </el-popconfirm>
                            </el-descriptions-item>
                        </el-descriptions>
                    </template>
                    <el-image :src="item.pic"
                              style="width: 100px; height: 100px"></el-image>
                </el-popover>
                <hr>
            </div>
        </div>
    </el-dialog>

    <el-dialog title="聊天室足迹" v-model="chatRoomFootprintsDialog.show" width="600">
        <div style="overflow: auto;max-height: 400px">
            <div v-for="item in chatRoomFootprintsDialog.data">
                <el-popover placement="right" trigger="hover">
                    <template #reference>
                        <el-descriptions title="房间信息">
                            <template #extra>
                                <el-button type="primary" @click="testEnterChatRoom(item.id)">加入</el-button>
                            </template>
                            <el-descriptions-item label="房间名称"><strong>{{item.name}}</strong></el-descriptions-item>
                            <el-descriptions-item label="房间id">{{item.id}}</el-descriptions-item>
                            <el-descriptions-item label="房间权限">
                                <span v-if="item.access == 1"><el-tag size="small">公开</el-tag></span>
                                <span v-if="item.access == 0"><el-tag size="danger">私密</el-tag></span>
                            </el-descriptions-item>
                        </el-descriptions>
                    </template>
                    <el-image :src="item.pic"
                              style="width: 100px; height: 100px"></el-image>
                </el-popover>
                <hr>
            </div>
        </div>
    </el-dialog>

    <el-dialog title="请输入密码" v-model="placeInputPwdDialog.show" width="400"
               @close="placeInputPwdDialog.closeDialog()">
        <div>
            <span style="font-weight: bold;color: red">私密房间,请输入密码!</span>
            <br>
            <el-input v-model="placeInputPwdDialog.data.roomPwd" type="password" show-password
                      placeholder="请输入密码"/>
        </div>
        <template #footer>
            <el-button type="primary" @click="placeInputPwdDialog.enter">确定</el-button>
            <el-button @click="placeInputPwdDialog.show = false">取消</el-button>
        </template>
    </el-dialog>


    <el-dialog :title="chartRoomDialog.data.name" v-model="chartRoomDialog.show" style="width: 700px;"
               @close="chartRoomDialog.closeDialog()">
        <div>
            <div style="margin-bottom: 10px">
                <span style="margin-right: 10px">房间id: {{chartRoomDialog.data.roomId}}</span>
                <span v-if="chartRoomDialog.data.access == 1"><el-tag size="small">公开</el-tag></span>
                <span v-if="chartRoomDialog.data.access == 0"><el-tag size="danger">私密</el-tag></span>
            </div>
            <div id="chat_panel" style="overflow: auto;height: 400px;border: 1px solid #ececec;margin-bottom: 20px">
                <div v-for="item in chartRoomDialog.data.allMsg">
                    <div class="message-box" v-if="item.username != '系统消息'">
                        <el-tooltip
                                class="box-item"
                                effect="dark"
                                :content="item.username"
                                placement="bottom"
                        >
                            <div class="chat-name-box">
                                <span class="chat-name">{{item.username}}</span>:
                            </div>
                        </el-tooltip>
                        <div class="content" style="width: 390px">
                            {{item.msg}}
                        </div>
                        <span style="color: #909399">{{formatDateTimeTo24Hour(item.sendTime)}}</span>
                    </div>
                    <div class="system-message" v-else>
                        {{item.msg}}
                    </div>
                </div>
            </div>
            <el-input v-model="chartRoomDialog.data.sendMsg" type="text" style="width: 85%"
                      placeholder="请输入消息"></el-input>
            <el-button type="primary" style="margin-left: 20px" @click="chartRoomDialog.sendMessage">发送</el-button>
        </div>
    </el-dialog>

    <el-dialog title="登录" v-model="loginDialog.show" width="350" @close="loginDialog.closeDialog()">
        <el-form>
            <el-form-item label="用户名* :" label-width="80">
                <el-input v-model="loginDialog.data.username" type="text" placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item label="密码* :" label-width="80">
                <el-input v-model="loginDialog.data.password" type="password" placeholder="请输入密码"/>
            </el-form-item>
            <div style="margin-left: 10px">
                如果无账号请先
                <el-link type="primary" @click="()=>{
                loginDialog.closeDialog();
                registerDialog.openDialog();
                }">注册
                </el-link>
            </div>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="loginDialog.login()">登录</el-button>
            <el-button @click="loginDialog.show = false">取消</el-button>
        </template>
    </el-dialog>

    <el-dialog title="注册" v-model="registerDialog.show" width="350" @close="registerDialog.closeDialog()">
        <el-form>
            <el-form-item label="用户名* :" label-width="90">
                <el-input v-model="registerDialog.data.username" type="text" placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item label="密码* :" label-width="90">
                <el-input v-model="registerDialog.data.password" type="password" placeholder="请输入密码"/>
            </el-form-item>
            <el-form-item label="确认密码* :" label-width="90">
                <el-input v-model="registerDialog.data.rePassword" type="password" placeholder="请输入密码"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="registerDialog.register()">注册</el-button>
            <el-button @click="registerDialog.show = false">取消</el-button>
        </template>
    </el-dialog>


    <el-dialog title="用户管理列表" v-model="userListDialog.show" @close="userListDialog.closeDialog()">
        <el-table :data="userListDialog.data" border style="width:100%" max-height="300">
            <el-table-column label="uid" prop="id"></el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="是否有效">
                <template #default="scope">
                    <el-switch v-model="scope.row.valid" :disabled="scope.row.id == 100000"
                               @change="userListDialog.updateUserValid(scope.row.id, scope.row.valid)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="是否管理员">
                <template #default="scope">
                    <el-switch v-model="scope.row.admin" :disabled="scope.row.id == 100000"
                               @change="userListDialog.updateUserAdmin(scope.row.id, scope.row.admin)"></el-switch>
                </template>
            </el-table-column>
        </el-table>
    </el-dialog>
</div>

<script>
    const {ElMessage} = ElementPlus;
    const url = "${pageContext.request.contextPath}";
    const {createApp, ref} = Vue;
    const App = {
        setup() {
            let userinfo = ref(null);

            let adminMode = ref({
                isAdmin: false,
                openAdminMode: false
            });

            const webUrl = ref(url);

            fetch(url + "/api/user/autoLogin")
                .then(res => res.json())
                .then(res => {
                    if (res.code == 200) {
                        userinfo.value = res.data;
                        verifyAdminUser();
                    }
                });

            function verifyAdminUser() {
                fetch(url + "/api/user/verifyAdminUserApi")
                    .then(res => res.json())
                    .then(res => {
                        if (res.code == 200) {
                            adminMode.value.isAdmin = true;
                            showSuccessMessage("管理员身份登录!");
                        }
                        console.log(res);
                    });
            }

            function logout() {
                userinfo.value = null;
                fetch(url + "/api/user/logout")
                    .then(res => res.json())
                    .then(res => {
                        showSuccessMessage(res.msg);
                        adminMode.value.isAdmin = false;
                        adminMode.value.openAdminMode = false;
                    });
            }

            let userListDialog = ref({
                show: false,
                openDialog: function () {
                    userListDialog.value.show = true;
                    fetch(url + "/api/user/getUserList_admin")
                        .then(res => res.json())
                        .then(res => {
                            if (res.code == 200) {
                                userListDialog.value.data = res.data;
                                console.log(res);
                            }
                        });
                },
                closeDialog: () => {
                    userListDialog.value.show = false;
                    userListDialog.value.data = [];
                },
                data: [],
                updateUserValid: function (uid, valid) {
                    //TODO:修改用户有效状态
                    let urlSearchParams = new URLSearchParams();
                    urlSearchParams.append("uid", uid);
                    urlSearchParams.append("valid", valid);
                    fetch(url + "/api/user/updateUserValid_admin", {
                        method: "post",
                        body: urlSearchParams
                    }).then(res => res.json())
                        .then(res => {
                            if (res.code != 200) {
                                showErrorMessage("修改用户有效失败");
                            }
                        });
                },
                updateUserAdmin: function (uid, admin) {
                    //TODO:修改用户管理员状态
                    let urlSearchParams = new URLSearchParams();
                    urlSearchParams.append("uid", uid);
                    urlSearchParams.append("valid", admin);
                    fetch(url + "/api/user/updateUserAdmin_admin", {
                        method: "post",
                        body: urlSearchParams
                    }).then(res => res.json())
                        .then(res => {
                            if (res.code != 200) {
                                showErrorMessage("修改用户管理员失败");
                            }
                        });
                }
            });

            let editChatRoomDialog = ref({
                show: false,
                title: "",
                event: {
                    success: function (res) {
                    },
                    error: function (res) {
                    }
                },
                fileInput: function () {
                    return document.querySelector("#file_pic_create_room");
                },
                openDialog: function (title, data, success, error) {
                    editChatRoomDialog.value.show = true;
                    this.title = title;
                    if (this.title.indexOf("修改") >= 0) {
                        for (let key in data) {
                            this.data[key] = data[key];
                            if (key == "id") {
                                this.data["roomId"] = data[key];
                            }
                        }
                    }
                    if (success)
                        this.event.success = success;
                    if (error)
                        this.event.error = error;
                },
                closeDialog: function () {
                    editChatRoomDialog.value.show = false;
                    for (let key in this.data) {
                        this.data[key] = null;
                    }
                    this.fileInput().value = "";
                    this.event.success = function (res) {
                    }
                    this.event.error = function (res) {
                    }
                },
                data: {
                    name: null,
                    access: null,
                    password: null,
                    pic: null,
                    roomId: null,
                },
                handleFileChange: function () {
                    if (this.fileInput().files.length > 0) {
                        this.data.pic = this.fileInput().files[0];
                    }
                },
                addNewRoom: function () {
                    if (!this.data.name || this.data.name.trim().length === 0) {
                        showErrorMessage("房间名称不能为空!");
                        return;
                    }
                    if (this.data.access == null) {
                        showErrorMessage("访问权限不能为空!")
                        return;
                    }
                    if (this.data.access == 0) {
                        const pwd = this.data.password;
                        if (!pwd || pwd.length < 4 || pwd.length > 20) {
                            showErrorMessage("访问密码应该在4-20之间");
                            return;
                        }
                    }
                    let formData = new FormData();
                    formData.append("name", this.data.name);
                    formData.append("access", this.data.access);
                    formData.append("password", this.data.password);
                    formData.append("pic", this.data.pic);
                    if (this.title.indexOf('创建') >= 0) {
                        fetch(url + "/api/chatroom/createNewChatRoom", {
                            method: "post",
                            body: formData
                        }).then((res) => {
                            return res.json();
                        }).then((res) => {
                            if (res.code == 200) {
                                showSuccessMessage(res.msg);
                                this.event.success(res);
                                this.closeDialog();
                            } else {
                                showErrorMessage(res.msg);
                                this.event.error(res);
                            }
                        });
                    } else if (this.title.indexOf('修改') >= 0) {
                        //TODO:编辑api
                        let formData1 = new FormData();
                        console.log(this.data);
                        formData1.append("id", this.data.roomId);
                        formData1.append("name", this.data.name);
                        formData1.append("access", this.data.access);
                        formData1.append("password", this.data.password);
                        formData1.append("pic", this.data.pic);
                        fetch(url + "/api/chatroom/updateChatRoomByRoomId", {
                            method: "post",
                            body: formData1,
                        })
                            .then(res => res.json())
                            .then(res => {
                                if (res.code == 200) {
                                    showSuccessMessage(res.msg);
                                    this.event.success(res);
                                    this.closeDialog();
                                } else {
                                    showErrorMessage(res.msg);
                                    this.event.error(res);
                                }
                            });
                    }
                }
            });

            let joinChatRoomDialog = ref({
                show: false,
                choose: null,
                openDialog: function () {
                    joinChatRoomDialog.value.show = true;
                },
                closeDialog: () => {
                    let val = joinChatRoomDialog.value;
                    val.show = false;
                    val.choose = null;
                    val.queryList = null;
                    for (let key in val.data) {
                        val.data[key] = null;
                    }
                },
                data: {
                    search: "",
                    id: null,
                    name: null,
                },
                queryList: null,
                handleSelect: function (item) {
                    Object.assign(joinChatRoomDialog.value.data, item);
                    if (adminMode.value.openAdminMode) {
                        fetch(url + "/api/user/getUserByUid_admin?uid=" + joinChatRoomDialog.value.data.createUserId)
                            .then(res => res.json())
                            .then(res => {
                                if (res.code == 200) {
                                    delete res.data.id;
                                    Object.assign(joinChatRoomDialog.value.data, res.data);
                                    joinChatRoomDialog.value.data.valid = item.valid;
                                } else {
                                    showErrorMessage(res.msg);
                                }
                            });
                    }
                    joinChatRoomDialog.value.data.search = item.name;
                },
                querySearch: function (query, cb) {
                    let newList = [];
                    for (let i = 0; i < joinChatRoomDialog.value.queryList.length; i++) {
                        if (joinChatRoomDialog.value.queryList[i].name.indexOf(query) >= 0) {
                            newList.push(joinChatRoomDialog.value.queryList[i]);
                        }
                    }
                    cb(newList);
                },
                handleChoose: function () {
                    if (joinChatRoomDialog.value.choose == 1 && joinChatRoomDialog.value.queryList == null) {
                        if (!adminMode.value.openAdminMode) {
                            fetch(url + "/api/chatroom/getAllChatRoom")
                                .then(res => res.json())
                                .then(res => {
                                    if (res.code == 200) {
                                        joinChatRoomDialog.value.queryList = res.data;
                                    } else {
                                        showErrorMessage(res.msg);
                                        joinChatRoomDialog.value.queryList = [];
                                    }
                                });
                        } else {
                            fetch(url + "/api/chatroom/getAllChatRoom_admin")
                                .then(res => res.json())
                                .then(res => {
                                    if (res.code == 200) {
                                        console.log(res);
                                        joinChatRoomDialog.value.queryList = res.data;
                                    } else {
                                        showErrorMessage(res.msg);
                                        joinChatRoomDialog.value.queryList = [];
                                    }
                                });
                        }
                    }
                },
                handleSubmit: function () {
                    let data = joinChatRoomDialog.value.data;
                    if (adminMode.value.openAdminMode) {
                        fetch(url + "/api/chatroom/getChatRoomByRoomId_admin?roomId=" + data.search)
                            .then(res => res.json())
                            .then(res => {
                                if (res.code == 200) {
                                    Object.assign(data, res.data);
                                    fetch(url + "/api/user/getUserByUid_admin?uid=" + data.createUserId)
                                        .then(res => res.json())
                                        .then(res => {
                                            if (res.code == 200) {
                                                delete res.data.id;
                                                Object.assign(data, res.data);
                                                data.valid = res.data.valid;
                                            } else {
                                                showErrorMessage(res.msg);
                                            }
                                        });
                                    showSuccessMessage("搜索成功")
                                } else {
                                    showErrorMessage(res.msg)
                                }
                            });
                    } else {
                        fetch(url + "/api/chatroom/getChatRoomByRoomId?roomId=" + data.search)
                            .then(res => res.json())
                            .then(res => {
                                if (res.code == 200) {
                                    Object.assign(data, res.data);
                                    showSuccessMessage("搜索成功")
                                } else {
                                    showErrorMessage(res.msg)
                                }
                            });
                    }
                },
                openOrCloseRoom: function (roomId) {
                    console.log(roomId);
                    let data = joinChatRoomDialog.value.data;
                    fetch(url + "/api/chatroom/openOrCloseChatRoom_admin?roomId=" + roomId)
                        .then(res => res.json())
                        .then(res => {
                            if (res.code == 200) {
                                data.valid = !data.valid;
                            } else {
                                showErrorMessage(res.msg);
                            }
                        });
                }
            });

            let myChatRoomDialog = ref({
                show: false,
                openDialog: () => {
                    myChatRoomDialog.value.show = true;
                    myChatRoomDialog.value.update();
                },
                closeDialog: () => {
                    myChatRoomDialog.value.show = false;
                },
                data: [],
                update: function () {
                    fetch(url + "/api/chatroom/getChatRoomByUid")
                        .then(res => res.json())
                        .then(res => {
                            if (res.code == 200) {
                                this.data = res.data;
                                // for (let i = 0; i < res.data.length; i++) {
                                //     this.data[i].createTime = formatDateTimeTo24Hour(this.data[i].createTime);
                                // }
                                console.log(this.data);
                            } else {
                                showErrorMessage(res.msg);
                            }
                        });
                },
                deleteRoom: function (roomId) {
                    fetch(url + "/api/chatroom/delChatRoomByRoomId?roomId=" + roomId)
                        .then(res => res.json())
                        .then(res => {
                            if (res.code == 200) {
                                myChatRoomDialog.value.update();
                                showSuccessMessage(res.msg);
                                return;
                            }
                            showErrorMessage(res.msg);
                        });
                },
                modifyRoom: function (item) {
                    editChatRoomDialog.value.openDialog("修改房间", item, function (res) {
                        setTimeout(function () {
                            showSuccessMessage("封面修改,需要刷新后才能显示预览");
                            myChatRoomDialog.value.update();
                        }, 500);
                    });
                }
            });

            let chatRoomFootprintsDialog = ref({
                show: false,
                openDialog: () => {
                    chatRoomFootprintsDialog.value.show = true;
                    chatRoomFootprintsDialog.value.update();
                },
                closeDialog: () => {
                    chatRoomFootprintsDialog.value.show = false;
                },
                data: [],
                update: function () {
                    fetch(url + "/api/user_footprints/getUserFootprintsByUid_orderByTime")
                        .then(res => res.json())
                        .then(res => {
                            if (res.code == 200) {
                                chatRoomFootprintsDialog.value.data = res.data;
                                console.log(res.data);
                            } else {
                                showErrorMessage(res.msg);
                            }
                        });
                }
            });

            let loginDialog = ref({
                show: false,
                openDialog: () => {
                    loginDialog.value.show = true;
                },
                closeDialog: function () {
                    loginDialog.value.show = false;
                    for (let key in this.data) {
                        this.data[key] = null;
                    }
                },
                data: {
                    username: "",
                    password: "",
                },
                login: function () {
                    let data = this.data;
                    const username = data.username.trim();
                    const password = data.password.trim();
                    if (!checkUsernamePassword(username, password)) {
                        return;
                    }
                    let urlSearchParams = new URLSearchParams();
                    urlSearchParams.append("username", username);
                    urlSearchParams.append("password", password);
                    fetch(url + "/api/user/login", {
                        method: "post",
                        body: urlSearchParams
                    }).then(res => res.json())
                        .then((json) => {
                            console.log(json);
                            if (json.code == 200) {
                                showSuccessMessage("登录成功!");
                                userinfo.value = json.data;
                                verifyAdminUser();
                                this.closeDialog();
                            } else {
                                showErrorMessage("登陆失败!" + json.msg + "!");
                            }
                        })
                }
            });

            let registerDialog = ref({
                show: false,
                openDialog: () => {
                    registerDialog.value.show = true;
                },
                closeDialog: function () {
                    registerDialog.value.show = false;
                    for (let key in this.data) {
                        this.data[key] = null;
                    }
                },
                data: {
                    username: "",
                    password: "",
                    rePassword: ""
                },
                register: function () {
                    const username = this.data.username.trim();
                    const password = this.data.password.trim();
                    const rePassword = this.data.rePassword.trim();
                    if (!checkUsernamePassword(username, password)) {
                        return;
                    }
                    if (rePassword !== password) {
                        showWarningMessage("密码不一致");
                        return;
                    }
                    let urlSearchParams = new URLSearchParams();
                    urlSearchParams.append("username", username);
                    urlSearchParams.append("password", password);
                    fetch(url + "/api/user/register", {
                        method: "post",
                        body: urlSearchParams
                    }).then(res => res.json())
                        .then((json) => {
                            if (json.code == 200) {
                                showSuccessMessage(json.msg);
                                this.closeDialog();
                            } else {
                                showErrorMessage(json.msg);
                            }
                        });
                }
            });

            let chartRoomDialog = ref({
                show: false,
                timer: function () {
                    console.log("更新");
                    let value = chartRoomDialog.value;
                    if (!value.data.roomId)
                        return;
                    let urlSearchParams = new URLSearchParams();
                    urlSearchParams.append("roomId", value.data.roomId);
                    urlSearchParams.append("roomPwd", value.data.password);
                    fetch(url + "/api/chatRoomMsg/getChatRoomMsg", {
                        method: "post",
                        body: urlSearchParams
                    }).then(res => res.json())
                        .then(res => {
                            console.log(res);
                            if (res.code == 200) {
                                value.setAllMsg(res.data);
                                if (value.startTimer)
                                    value.startTimer();
                            } else {
                                showErrorMessage(res.msg);
                                value.closeDialog();
                            }
                        });
                },
                startTimer: null,
                openDialog: (list, pwd, roomId) => {
                    console.log(list, pwd, roomId);
                    if (list)
                        chartRoomDialog.value.setAllMsg(list);
                    if (pwd)
                        chartRoomDialog.value.data.password = pwd;
                    if (roomId) {
                        chartRoomDialog.value.data.roomId = roomId;
                        chartRoomDialog.value.show = true;
                        fetch(url + "/api/chatroom/getChatRoomByRoomId?roomId=" + roomId)
                            .then(res => res.json())
                            .then(res => {
                                if (res.code == 200) {
                                    let val = chartRoomDialog.value;
                                    val.data.roomId = res.data.id;
                                    val.data.name = res.data.name;
                                    val.data.access = res.data.access;
                                    let element = document.querySelector("#chat_panel");
                                    element.scrollTop = element.scrollHeight;
                                    val.startTimer = function () {
                                        setTimeout(val.timer, 5000);
                                    }
                                    val.startTimer();
                                } else {
                                    showErrorMessage(res.msg);
                                    chartRoomDialog.value.closeDialog();
                                }
                            });
                    }
                },
                closeDialog: function () {
                    chartRoomDialog.value.show = false;
                    for (let key in this.data) {
                        this.data[key] = null;
                    }
                    chartRoomDialog.value.startTimer = null;
                },
                data: {
                    name: null,
                    sendMsg: null,
                    allMsg: null,
                    password: null,
                    roomId: null
                },
                sendMessage: function () {
                    let value = chartRoomDialog.value.data;
                    if (value.sendMsg != null && value.sendMsg.length > 0) {
                        sendMessage(value.roomId, value.password, value.sendMsg, (res) => {
                            if (res.code != 200) {
                                showErrorMessage(res.msg);
                            } else {
                                chartRoomDialog.value.setAllMsg(res.data);
                                value.sendMsg = "";
                            }
                        });
                    }
                },
                setAllMsg: function (list) {
                    if (list) {
                        let val = chartRoomDialog.value.data;
                        val.allMsg = [];
                        let index = -1;
                        if (list.length > 0) {
                            val.allMsg.push(list[0]);
                            index = 0;
                        }
                        for (let i = 1; i < list.length; i++) {
                            if (val.allMsg[index].msg == list[i].msg) {
                                continue;
                            }
                            val.allMsg.push(list[i]);
                            index++;
                        }
                    }
                }
            });

            let placeInputPwdDialog = ref({
                show: false,
                openDialog: (roomId) => {
                    placeInputPwdDialog.value.show = true;
                    let data = placeInputPwdDialog.value.data;
                    data.roomId = roomId;
                },
                closeDialog: function () {
                    placeInputPwdDialog.value.show = false;
                    for (let key in this.data) {
                        this.data[key] = null;
                    }
                },
                data: {
                    roomId: null,
                    roomPwd: null
                },
                enter: function () {
                    let data = placeInputPwdDialog.value.data;
                    enterChatRoom(data.roomId, data.roomPwd, (res) => {
                        if (res.code == 200) {
                            console.log(data);
                            chartRoomDialog.value.openDialog(res.data, data.roomPwd, data.roomId);
                            placeInputPwdDialog.value.closeDialog();
                        } else {
                            showErrorMessage("加入房间失败");
                        }
                    });
                }
            });

            function showSuccessMessage(msg) {
                ElMessage({
                    message: msg,
                    type: 'success',
                })
            }

            function showMessage(msg) {
                ElMessage(msg);
            }

            function showWarningMessage(msg) {
                ElMessage({
                    message: msg,
                    type: 'warning',
                })
            }

            function showErrorMessage(msg) {
                ElMessage.error(msg)
            }

            function sendMessage(roomId, roomPwd, msg, cb) {
                let urlSearchParams = new URLSearchParams();
                urlSearchParams.append("roomId", roomId);
                urlSearchParams.append("roomPwd", roomPwd);
                urlSearchParams.append("message", msg);
                fetch(url + "/api/chatRoomMsg/sendMessage", {
                    method: "post",
                    body: urlSearchParams
                })
                    .then(res => res.json())
                    .then(res => {
                        cb(res);
                    });
            }

            function enterChatRoom(roomId, roomPwd, cb) {
                let urlSearchParams = new URLSearchParams();
                urlSearchParams.append("roomId", roomId);
                urlSearchParams.append("roomPwd", roomPwd);
                fetch(url + "/api/chatRoomMsg/enterChatRoomMsg", {
                    method: "post",
                    body: urlSearchParams
                }).then(res => res.json())
                    .then(res => {
                        if (res)
                            cb(res)
                    });
            }

            function testEnterChatRoom(roomId) {
                let urlSearchParams = new URLSearchParams();
                urlSearchParams.append("roomId", roomId);
                urlSearchParams.append("roomPwd", "");
                fetch(url + "/api/chatRoomMsg/enterChatRoomMsg", {
                    method: 'post',
                    body: urlSearchParams
                })
                    .then(res => res.json())
                    .then(res => {
                        console.log(res);
                        if (res.code == 200) {
                            chartRoomDialog.value.openDialog(res.data, "", roomId);
                        } else {
                            if (res.msg.indexOf("登录") >= 0) {
                                showErrorMessage(res.msg);
                                return;
                            }
                            placeInputPwdDialog.value.openDialog(roomId);
                        }
                    });
            }

            function checkUsernamePassword(username, password) {
                if (!username || username.length > 20 || username.length === 0) {
                    showErrorMessage("用户名不能为空,且小于20长度!");
                    return false;
                }
                if (!password || password.length > 20 || password.length < 6) {
                    showErrorMessage("密码不能为空,且必须在6-20之间");
                    return false;
                }
                return true;
            }

            function formatDateTimeTo24Hour(input) {
                const monthMap = {
                    Jan: '01', Feb: '02', Mar: '03', Apr: '04',
                    May: '05', Jun: '06', Jul: '07', Aug: '08',
                    Sep: '09', Oct: '10', Nov: '11', Dec: '12'
                };
                const [monthStr, day, yearStr, timeStr, period] = input.split(/,\s|:\s| /);
                const month = monthMap[monthStr];
                const hours = (period === 'PM' && timeStr.split(':')[0] !== '12') ? parseInt(timeStr.split(':')[0], 10) + 12 : parseInt(timeStr.split(':')[0], 10);
                const [minutes, seconds] = timeStr.split(':').slice(1);
                const formattedDate = yearStr + '-' +
                    month + '-' +
                    day.padStart(2, '0') + ' ' +
                    hours.toString().padStart(2, '0') + ':' +
                    minutes.padStart(2, '0') + ':' +
                    seconds.padStart(2, '0');
                return formattedDate;
            }

            return {
                userListDialog,
                adminMode,
                webUrl,
                logout,
                userinfo,
                enterChatRoom,
                editChatRoomDialog,
                joinChatRoomDialog,
                myChatRoomDialog,
                chatRoomFootprintsDialog,
                chartRoomDialog,
                loginDialog,
                registerDialog,
                formatDateTimeTo24Hour,
                placeInputPwdDialog,
                testEnterChatRoom
            }
        }
    };
    const app = createApp(App);
    app.use(ElementPlus);
    app.mount("#app");
</script>
</body>
</html>
